package com.example.map_navi_plugin;

import android.content.Context;
import android.content.res.AssetManager;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;

/**
 * Created by KayoXu on 2018/2/1.
 */

public class GsonUtils {

    /**
     * @param gsonString jsonStr
     * @param type       类型
     * @param <T>
     * @return JavaBean
     */
    public static <T> T gsonToBean(String gsonString, Type type) {
        Gson gson = new Gson();// new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.fromJson(gsonString, type);
    }

    /**
     * @param gsonString jsonStr
     * @param cls        JavaBean.class
     * @param <T>        T
     * @return JavaBean
     */
    public static <T> T gsonToBean(String gsonString, Class<T> cls) {
        Gson gson = new Gson();
        return gson.fromJson(gsonString, cls);
    }


    public static <T> String beanToJson(T t) {

        Gson gson = new Gson();
        return gson.toJson(t);

    }

    public static String toJson(Object t) {
        if (null == t) return "";
        Gson gson = new Gson();
        return gson.toJson(t);

    }

    /**
     * 测试时用的, 没啥用
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        AssetManager assetManager = context.getAssets();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


}
